package cn.itcast.service.system.impl;

import cn.itcast.dao.system.ModuleDao;
import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ModuleServiceImpl implements ModuleService {

    @Autowired
    private ModuleDao moduleDao;

    @Override
    public List<Module> findAll() {
        return moduleDao.findAll();
    }

    @Override
    public Module findById(String id) {
        return moduleDao.findById(id);
    }

    @Override
    public void save(Module module) {
        moduleDao.save(module);
    }

    @Override
    public void updateById(Module module) {
        moduleDao.updateById(module);
    }

    @Override
    public void deleteById(String id) {
        moduleDao.deleteById(id);
    }

    @Override
    public PageInfo<Module> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Module> list = moduleDao.findAll();
        return new PageInfo<>(list, 5);
    }

    @Override
    public void updateRoleModule(String roleid, String moduleIds) {
        moduleDao.deleteRoleAndModuleByRoleid(roleid);
        String[] moduleIdArr = moduleIds.split(",");
        for (String moduleId : moduleIdArr) {
            moduleDao.saveRoleAndModuleByRoleid(roleid, moduleId);
        }
    }

    @Override
    public List<String> findRoleModuleByRoleid(String roleid) {
        return moduleDao.findRoleModuleByRoleid(roleid);
    }

    @Override
    public List<Module> findModulesByUser(User user) {
        Integer degree = user.getDegree();
        List<Module> modules = null;
        if (degree == 0) {
            modules = moduleDao.findByBelong(0);
        } else if (degree == 1) {
            modules = moduleDao.findByBelong(1);
        } else {
            modules = moduleDao.findModuleByUserId(user.getId());
        }
        return modules;
    }
}
